package service;

import model.Message;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class SendMessage extends JFrame implements ActionListener, Runnable {

    JLabel jl1, jl2;
    JButton jb1;
    JTextArea jta, jta1;
    JScrollPane jsp, jsp1;
    Integer sendId, getId;
    Socket socket;

    public SendMessage(Integer sendId, Integer getId, Socket socket) {
        this.sendId = sendId;
        this.getId = getId;
        this.socket = socket;
        jl1 = new JLabel("你在和" + getId + "进行对话");
        jl1.setBounds(10, 10, 550, 20);
        jl1.setBackground(Color.lightGray);
        jl1.setFont(new Font("宋体", Font.BOLD, 20));
        add(jl1);

        jl2 = new JLabel("请输入你想说的话");
        jl2.setBounds(10, 350, 550, 20);
        jl2.setFont(new Font("宋体", Font.BOLD, 20));
        add(jl2);

        jta = new JTextArea();
        jsp = new JScrollPane(jta);
        jsp.setBounds(0, 40, 537, 300);
        add(jsp);

        jta1 = new JTextArea();
        jsp1 = new JScrollPane(jta1);
        jsp1.setBounds(0, 380, 537, 100);
        add(jsp1);

        jb1 = new JButton("发送");
        jb1.setBounds(436, 480, 100, 32);
        jb1.addActionListener(this);
        add(jb1);

        setLayout(null);
        setLocation(600, 150);
        setSize(550, 550);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setResizable(false);
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        ObjectOutputStream os = null;
        if (e.getSource() == jb1) {

            String sendMessage = jta1.getText().trim();
            jta.setText(jta.getText() + "\n" + "你对" + sendId + "说" + sendMessage);
            jta1.setText("");
            Message message = new Message(sendId, getId, sendMessage);

            try {
                os = new ObjectOutputStream(socket.getOutputStream());
                os.writeObject(message);
            } catch (IOException e1) {
                e1.printStackTrace();

            }
        }
    }

    @Override
    public void run() {
        ObjectInputStream is = null;
        while (true) {
            try {
                is = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) is.readObject();
                jta.setText(jta.getText() + "\n" + message.getGet_id() + "对你说" + message.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
